#pragma once
#include <iostream>
#include <string>
#include <unordered_map>

namespace Users
{
    class user
    {
    public:
       user(const std::string& ip,const uint16_t& port):_ip(ip),_port(port)
       {}

       uint16_t& getPort(){return _port;}
       std::string getIp(){return _ip;}

    private:
      uint16_t _port;
      std::string _ip;
    };

    class onLineUser
    {
    public:
        onLineUser()
        {}
        ~onLineUser()
        {}

        void addUser(const std::string ip,const uint16_t port)
        {
             std::string name = ip + std::to_string(port);
             _users.insert(make_pair(name,user(ip,port)));
        }

        bool delUser(const std::string ip,const uint16_t port)
        {
            std::string name = ip + std::to_string(port);
            auto it = _users.find(name);
            if(it == _users.end())
            {
                std::cout << "在线成员中，没有" << name << "成员" << std::endl;
                return false;
            }
            _users.erase(it);
            return true;
        } 

        bool is_online(const std::string ip,const uint16_t port)
        {
            std::string name = ip + std::to_string(port);
            auto it = _users.find(name);
            return it == _users.end() ? false : true; 
        }
        //给每个用户都发个信息
        void boreacast(int sockfd,std::string ip,std::uint16_t port,std::string message)
        {
             //在这里我们要群发信息给每一个客户端
             
             for(auto & e : _users)
             {
                std::string send = ip;
                send += '[';
                send += std::to_string(port);
                send += "]#";
                send += message;

                struct  sockaddr_in address;
                bzero(&address,sizeof(address));
                address.sin_family = AF_INET;
                address.sin_port = htons(e.second.getPort());
                address.sin_addr.s_addr = inet_addr(e.second.getIp().c_str());

                sendto(sockfd,send.c_str(),send.size(),0,(struct sockaddr*)&address,sizeof(address));
             }
        }

    private:
    std::unordered_map<std::string,user> _users; 
    };
}